/**
 * Created by weng on 2017/8/16.
 */

var data_temp = {};
var  temp_page_size= 15;

/**
 * 获取在院名单
 * @param info
 */
var getNurseList = function () {
    console.log("获取信息");
    var obj = {};
    var phone = $("#phone").val();
    if(phone)
        obj.phone = phone;
    $.ajax({
        url:'/hospital/getNurseList',
        type:'post',
        dataType:'json',
        data:obj,
        success:function(data) {
            console.log("data:",data);

            if (data.code != 200) {
                alert("查询错误");
                return;
            } else {
                if(data.info.length > 0){
                    data_temp = data.info
                    var temp_teble_info = data_temp.slice(0 , temp_page_size);
                    createPageMin(temp_page_size, 5, Math.ceil(data_temp.length), data_temp);
                    showTableInfo(temp_teble_info);
                }

            }
        }
    });
};

var getGovernorList = function () {
    console.log("获取信息");
    var obj = {};
    var phone = $("#phone").val();
    if(phone)
        obj.phone = phone;
    $.ajax({
        url:'/hospital/getGovernorList',
        type:'post',
        dataType:'json',
        data:obj,
        success:function(data) {
            console.log("data:",data);

            if (data.code != 200) {
                alert("查询错误");
                return;
            } else {
                if(data.info.length > 0){
                    data_temp = data.info
                    var temp_teble_info = data_temp.slice(0 , temp_page_size);
                    createPageMin(temp_page_size, 5, Math.ceil(data_temp.length), data_temp);
                    showTableInfo(temp_teble_info);
                }

            }
        }
    });
};



function createPageMin(pageSize, buttons, total,data_temp) {
    $("#pagination").empty();
    $('#pagination').Paging({pagesize:pageSize,count:total,toolbar:true,pageSizeList:[temp_page_size],
        callback:function(page,size,count){
            page = page - 1;
            var temp_teble_info = data_temp.slice(page  * size ,page * pageSize + size);
            showTableInfo(temp_teble_info);
        }});
}


function showTableInfo(data_arr){
    var html = "";
    var thead = $('#taccountList thead');
    var tbody = $('#taccountList tbody');
    tbody.empty();
    thead.empty();
    var htmlHead = "<tr>"
        + "<th>护工编号：</th>"
        + "<th>护工姓名：</th>"
        + "<th>性别：</th>"
        + "<th>手机号：</th>"
        + "<th>上岗日期：</th>"
        + "<th>操作：</th>"
        + "</tr>"
    htmlHead = $(htmlHead);
    thead.append(htmlHead);

    for(var i in data_arr){
        html += '<tr>' +
            '<th  id="id'+ data_arr[i].id +'" style="display: none">'+  data_arr[i].id + '</th>' +
            '<th  id="id'+ data_arr[i].id +'">'+  data_arr[i].employeeUin + '</th>' +
            '<th  id="name'+ data_arr[i].id +'">'+  data_arr[i].name + '</th>' +
            '<th  id="sex'+ data_arr[i].id +'">'+  data_arr[i].sex + '</th>' +

            '<th  id="phone'+ data_arr[i].id +'">'+  data_arr[i].phone + '</th>' +
            '<th  id="onDuty'+ data_arr[i].id +'">'+  data_arr[i].onDuty + '</th>' +
            "<th>" +
            "<a onclick='changeToDetail("+ data_arr[i].id +")'>详情</a>" +
            '</th>' +
            '</tr>'
    }


    var tr = $(html);
    tbody.append(tr);
}

var changeToDetail = function (id) {
    console.log("id is:",id);
    layer.open({
            type: 2,
            title: '',
            //area: ['1000px', 'auto'],
            maxmin: true,
            //width:'200px',
            area: ['1266px', '720px'],
            content: '/boss/empoloyeeInfo?id=' + id,
            end: function(){
               // $.layer.tips('Hi', '#about', {tips: 1})
            }
        });
}

var updatePhone = function (id) {
    var obj = {};
    obj.phone = $("#phone"+ id).val();
    obj.id =id;

    $.ajax({
        url:'/hospital/updatePhone',
        type:'post',
        dataType:'json',
        data:obj,
        success:function(data){
            if(200 === data.code) {
                location.reload();
            }
            alert(data.info)
        }
    });
};






var updateTaccount = function () {
    layer.msg('确认修改信息？', {
        time: 0 //不自动关闭
        ,btn: ['确定', '取消']
        ,yes: function(index){
            var obj = {};
            obj.id = $("#id").val();
            obj.employeeUin = $("#employeeUin").val();
            obj.sex = $("#sex").val();
            obj.phone = $("#phone").val();
            obj.birthday = $("#birthday").val();
            obj.IdCard = $("#IdCard").val();
            obj.onDuty = $("#onDuty").val();
            obj.workYears = $("#workYears").val();
            obj.outDuty = $("#outDuty").val();
            obj.address = $("#address").val();
            obj.koseki = $("#koseki").val();
            obj.resume = $("#resume").val();
            obj.matePhone = $("#matePhone").val();
            obj.childrenPhone = $("#childrenPhone").val();
            obj.culture = $("#culture").val();
            obj.type = $("#type").val();

            console.log("obj is :",obj);

            var formData = new FormData();
            formData.append('files',$("#btn_file")[0].files[0]);
            formData.append('obj',JSON.stringify(obj));

            var url="/hospital/updateEmployee";
            $.ajax({
                url:url,
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                success:function(data){
                    layer.close(index);
                    if(200 === data.code) {
                        layer.msg('修改成功', {
                            icon: 1,
                            time: 1000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                            location.reload();
                        });
                    }else {
                        layer.msg(data.info );
                    }
                }
            });
        }
    });
}





var readControle = function () {
    if(!$('#employeeUin').attr("readonly")){
        $('input').attr("readonly","readonly");
        $('#sub').attr("disabled","disabled");

        $('input').addClass('disableClass');
        $('.input-group-addon').addClass('disableClass');

        $("input").css("background-color","black");

        $(".input-group .btn-primary").css("display","none");
        $(".input-group .btn-success").css("display","block");
        //  $("input").css("border","none");
        //  $("input").css("color","white");

        $('#readControle').text("允许更改");
        $("#sub").css('display','none');
    }else {
        $('#sub').removeAttr("disabled");
        $('input').removeAttr("readonly");
        $("#sub").css('display','block');

        $('input').removeClass('disableClass');
        $('.input-group-addon').removeClass('disableClass');
        $("input.form-control").css("background-color","#eee");

        $(".input-group .btn-primary").css("display","block");
        $(".input-group .btn-success").css("display","none");

        $('#readControle').text("禁止更改");
    }
}




var AddEmployee = function () {
    var obj = {};
    obj.employeeUin = $("#id").val();
    obj.name = $("#name").val();
    obj.sex = $("#sex").val();
    obj.phone = $("#phone").val();
    obj.birthday = $("#birthday").val();
    obj.onDuty = $("#onDuty").val();
    obj.type = $("#type").val();

    if(!obj.employeeUin){
        return  layer.msg('员工编号必须填写');
    }else if(!obj.name ){
        return  layer.msg('姓名必须填写');
    }else if(!obj.sex ){
        return  layer.msg('性别必须填写');
    }else if(!obj.phone ){
        return  layer.msg('电话号码必须填写');
    }else if(obj.phone.length > 11 ){
        return  layer.msg('电话号码长度不可超过11位');
    }
    else if(!obj.birthday ){
        obj.birthday = "";
        //return  layer.msg('出生年月必须填写');
    }
    $.ajax({
        url:'/hospital/AddEmployee',
        type:'post',
        dataType:'json',
        data:obj,
        success:function(data){
            alert(data.info)
            if(200 === data.code) {
                history.go(-1)
            }
        }
    });
};



function showMore() {
    $('#calendarDiv').css("display",'block');
    var id = $("#employeeUin").val();
    var type = $("#type").val();
    var obj = {id:id,type:type};

    $.ajax({
        url:'/hospital/getEmployeeDetail',
        type:'post',
        dataType:'json',
        data:obj,
        success:function(data){
            console.log("获取员工额外信息");

            if(200 === data.code) {
                var  dataMin = data.info;
                var  dataSource = [];
                for(var i in dataMin){
                    dataMin[i].startDate = new Date(dataMin[i].startDate)
                    dataMin[i].endDate = new Date(dataMin[i].endDate)
                    dataSource.push(dataMin[i]);
                }

                $('#calendar').calendar({
                    enableContextMenu: true,
                    enableRangeSelection: true,
                    contextMenuItems:[
                        {
                            text: '删除',
                            click: deleteEvent
                        }
                    ],
                    selectRange: function(e) {
                        editEvent({ startDate: e.startDate, endDate: e.endDate });
                    },
                    mouseOnDay: function(e) {
                        if(e.events.length > 0) {
                            var content = '';

                            for(var i in e.events) {
                                content += '<div class="event-tooltip-content ">'
                                    + '<div class="event-name" style="color:' + e.events[i].color + '">' + e.events[i].title + '</div>'
                                    + '<div class="event-location">' + e.events[i].content + '</div>'
                                    //+ '<img class="event-location" src="' + e.events[i].content + '"</imf>'
                                    + '</div>';
                            }
                            //bootstrap.min.css 修改power的max-width
                            $(e.element).popover({
                                trigger: 'manual',
                                container: 'body',
                                html:true,
                                content: content
                            });

                            $(e.element).popover('show');
                        }
                    },
                    mouseOutDay: function(e) {
                        if(e.events.length > 0) {
                            $(e.element).popover('hide');
                        }
                    },
                    dayContextMenu: function(e) {
                        $(e.element).popover('hide');
                    },
                    dataSource: dataSource
                });
            }
        }
    });


}


function editEvent(event) {
    console.log("是否允许编辑：",$('#employeeUin').attr("readonly"))

    if($('#employeeUin').attr("readonly")){
        return;
    }

    $('#event-modal input[name="event-index"]').val(event ? event.id : '');
    $('#event-modal input[name="event-name"]').val(event ? event.title : '');
    $('#event-modal input[name="event-location"]').val(event ? event.content : '');
    $('#event-modal input[name="event-start-date"]').datepicker('update', event ? event.startDate : '');
    $('#event-modal input[name="event-end-date"]').datepicker('update', event ? event.endDate : '');

     index = layer.open({
        type: 1,
        title: '',
        area: ['50%', 'auto'],
        content: $('#event-modal'),

    });
}

function deleteEvent(event) {
    console.log("event",event)
    var obj = {
        id: event.id,
    }
    console.log("obj",obj)
    $.ajax({
        url:'/hospital/deleteEmployeeDetail',
        type:'post',
        dataType:'json',
        data:obj,
        success:function(data){
            if(200 === data.code) {
                location.reload();
            }
        }
    });
}


function saveEvent() {
    var event = {
        employeeUin: $("#employeeUin").val(),
        type: $("#type").val(),
        id: $('#event-modal input[name="event-index"]').val(),
        title: $('#event-modal input[name="event-name"]').val(),
        content: $('#event-modal input[name="event-location"]').val(),
        startDate: $('#event-modal input[name="event-start-date"]').datepicker('getDate'),
        endDate: $('#event-modal input[name="event-end-date"]').datepicker('getDate')
    };

    if(!event.title || !event.content){
        layer.msg("事件类型和内容必须填写");
        return;
    }
    $.ajax({
        url:'/hospital/AddEmployeeDetail',
        type:'post',
        dataType:'json',
        data:event,
        success:function(data){
            if(200 === data.code) {
                location.reload();
            }
        }
    });

    layer.close(index);
}